import { useState, useEffect, useContext, useRef } from 'react'
import { View, Text, ScrollView, Input } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { AppContext } from '../../store'
import { getLocale } from '../../i18n'
import { dataManager } from '../../utils/dataManager'
import { deepSeekService, ChatMessage } from '../../services/deepseek'
import { ArtifactBase } from '../../types/artifact'
import './chat.scss'

interface Message {
  id: string
  role: 'user' | 'assistant'
  content: string
  reasoning?: string  // 思考过程
  timestamp: number
  reasoningCollapsed?: boolean  // 思考过程是否折叠
}

// 聊天记录存储键名前缀
const CHAT_STORAGE_PREFIX = 'chat_history_'

// 最大上下文消息条数（用于控制API请求的历史消息数量）
const MAX_CONTEXT_MESSAGES = 20

function ArtifactChat() {
  const { state } = useContext(AppContext)
  const i18n = getLocale(state.locale)
  const [artifact, setArtifact] = useState<ArtifactBase | null>(null)
  const [messages, setMessages] = useState<Message[]>([])
  const [inputValue, setInputValue] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const scrollViewRef = useRef<any>(null)

  // 切换思考过程的折叠状态
  const toggleReasoning = (messageId: string) => {
    setMessages(prev => prev.map(msg => 
      msg.id === messageId 
        ? { ...msg, reasoningCollapsed: !msg.reasoningCollapsed }
        : msg
    ))
  }

  useEffect(() => {
    // 获取路由参数
    const instance = Taro.getCurrentInstance()
    const id = instance.router?.params.id
    
    if (id) {
      loadArtifact(id)
    } else {
      Taro.showToast({
        title: i18n.common.error,
        icon: 'none'
      })
      setTimeout(() => {
        Taro.navigateBack()
      }, 1500)
    }
  }, [])

  const loadArtifact = (id: string) => {
    const data = dataManager.getArtifactById(id)
    if (data) {
      setArtifact(data)
      // 设置导航栏标题
      Taro.setNavigationBarTitle({
        title: `${i18n.chat.title} - ${data.getName(state.locale)}`
      })
      // 加载历史聊天记录
      loadChatHistory(id)
    } else {
      Taro.showToast({
        title: i18n.common.error,
        icon: 'none'
      })
      setTimeout(() => {
        Taro.navigateBack()
      }, 1500)
    }
  }

  // 加载历史聊天记录
  const loadChatHistory = (artifactId: string) => {
    try {
      const storageKey = `${CHAT_STORAGE_PREFIX}${artifactId}`
      const savedMessages = Taro.getStorageSync(storageKey)
      
      if (savedMessages && Array.isArray(savedMessages) && savedMessages.length > 0) {
        console.log(`加载文物 ${artifactId} 的聊天记录，共 ${savedMessages.length} 条`)
        setMessages(savedMessages)
      } else {
        // 没有历史记录，添加欢迎消息
        if (artifact) {
          addWelcomeMessage(artifact)
        }
      }
    } catch (error) {
      console.error('加载聊天记录失败:', error)
      // 加载失败时添加欢迎消息
      if (artifact) {
        addWelcomeMessage(artifact)
      }
    }
  }

  // 保存聊天记录到本地存储
  const saveChatHistory = (artifactId: string, msgs: Message[]) => {
    try {
      const storageKey = `${CHAT_STORAGE_PREFIX}${artifactId}`
      Taro.setStorageSync(storageKey, msgs)
      console.log(`保存文物 ${artifactId} 的聊天记录，共 ${msgs.length} 条`)
    } catch (error) {
      console.error('保存聊天记录失败:', error)
    }
  }

  const addWelcomeMessage = (artifact: ArtifactBase) => {
    const welcomeText = i18n.chat.welcome.replace('{name}', artifact.getName(state.locale))
    const message: Message = {
      id: Date.now().toString(),
      role: 'assistant',
      content: welcomeText,
      timestamp: Date.now()
    }
    setMessages([message])
    // 保存欢迎消息
    if (artifact.id) {
      saveChatHistory(artifact.id, [message])
    }
  }

  // 清空聊天记录
  const clearChatHistory = () => {
    if (!artifact) return

    Taro.showModal({
      title: state.locale === 'zh' ? '清空聊天记录' : 'Clear Chat History',
      content: state.locale === 'zh' 
        ? '确定要清空所有聊天记录吗？此操作不可恢复。' 
        : 'Are you sure you want to clear all chat history? This action cannot be undone.',
      success: (res) => {
        if (res.confirm) {
          // 清空消息列表并添加欢迎消息
          addWelcomeMessage(artifact)
          
          Taro.showToast({
            title: state.locale === 'zh' ? '已清空' : 'Cleared',
            icon: 'success',
            duration: 1500
          })
        }
      }
    })
  }

  const handleSend = async () => {
    if (!inputValue.trim()) {
      Taro.showToast({
        title: i18n.chat.inputEmpty,
        icon: 'none'
      })
      return
    }

    console.log('当前 state.apiKey:', state.apiKey)
    console.log('当前 state.apiKey 长度:', state.apiKey.length)
    console.log('从存储读取的 apiKey:', Taro.getStorageSync('apiKey'))
    
    if (!state.apiKey) {
      Taro.showToast({
        title: i18n.chat.apiKeyMissing,
        icon: 'none',
        duration: 2000
      })
      return
    }

    if (!artifact) return

    // 添加用户消息
    const userMessage: Message = {
      id: Date.now().toString(),
      role: 'user',
      content: inputValue,
      timestamp: Date.now()
    }

    setMessages(prev => {
      const newMessages = [...prev, userMessage]
      // 保存到本地存储
      saveChatHistory(artifact.id, newMessages)
      return newMessages
    })
    const currentInput = inputValue
    setInputValue('')
    setIsLoading(true)

    // 滚动到底部
    setTimeout(scrollToBottom, 100)

    // 创建临时AI消息用于流式更新
    const aiMessageId = (Date.now() + 1).toString()
    const tempAiMessage: Message = {
      id: aiMessageId,
      role: 'assistant',
      content: '',
      reasoning: '',
      reasoningCollapsed: true,  // 默认折叠
      timestamp: Date.now()
    }
    
    setMessages(prev => [...prev, tempAiMessage])

    try {
      // 构建聊天历史 - 智能上下文管理
      const welcomeText = i18n.chat.welcome.replace('{name}', artifact.getName(state.locale))
      const filteredMessages = messages.filter(msg => 
        msg.role !== 'assistant' || msg.content !== welcomeText
      )
      
      // 限制上下文消息数量，只取最近的 MAX_CONTEXT_MESSAGES 条
      const recentMessages = filteredMessages.slice(-MAX_CONTEXT_MESSAGES)
      
      const chatHistory: ChatMessage[] = recentMessages.map(msg => ({
        role: msg.role as 'user' | 'assistant',
        content: msg.content
      }))
      
      console.log(`发送上下文消息数: ${chatHistory.length} (总消息数: ${messages.length}, 限制: ${MAX_CONTEXT_MESSAGES})`)

      // 调用流式AI服务
      await deepSeekService.chatWithArtifactStream(
        artifact.getAiPrompt(state.locale),
        currentInput,
        chatHistory,
        {
          onReasoning: (text) => {
            // 更新思考过程
            setMessages(prev => prev.map(msg => 
              msg.id === aiMessageId 
                ? { ...msg, reasoning: (msg.reasoning || '') + text }
                : msg
            ))
            setTimeout(scrollToBottom, 50)
          },
          onContent: (text) => {
            // 更新回复内容
            setMessages(prev => prev.map(msg => 
              msg.id === aiMessageId 
                ? { ...msg, content: msg.content + text }
                : msg
            ))
            setTimeout(scrollToBottom, 50)
          },
          onComplete: () => {
            setIsLoading(false)
            // 保存完整对话到本地存储
            setMessages(prev => {
              saveChatHistory(artifact.id, prev)
              return prev
            })
          },
          onError: (error) => {
            console.error('流式响应错误:', error)
            setIsLoading(false)
          }
        }
      )
    } catch (error: any) {
      console.error('AI对话失败:', error)
      // 移除临时消息
      setMessages(prev => prev.filter(msg => msg.id !== aiMessageId))
      
      Taro.showToast({
        title: error.message || i18n.chat.errorMessage,
        icon: 'none',
        duration: 2000
      })
      setIsLoading(false)
    }
  }

  const scrollToBottom = () => {
    // 滚动到底部的逻辑
    if (scrollViewRef.current) {
      // Taro的ScrollView需要使用scrollIntoView
    }
  }

  if (!artifact) {
    return (
      <View className='chat-container'>
        <View className='loading-wrapper'>
          <Text className='loading-text'>{i18n.common.loading}</Text>
        </View>
      </View>
    )
  }

  return (
    <View className='chat-container'>
      {/* 文物信息卡片 */}
      <View className='artifact-card'>
        <Text className='artifact-icon'>🏛️</Text>
        <View className='artifact-card-info'>
          <Text className='artifact-card-name'>{artifact.getName(state.locale)}</Text>
          <Text className='artifact-card-dynasty'>
            {state.locale === 'zh' ? artifact.dynasty : artifact.dynastyEn}
          </Text>
        </View>
        {/* 清空聊天记录按钮 */}
        <View className='clear-button' onClick={clearChatHistory}>
          <Text className='clear-icon'>🗑️</Text>
        </View>
      </View>

      {/* 消息列表 */}
      <ScrollView 
        scrollY 
        className='messages-scroll'
        scrollIntoView={`msg-${messages[messages.length - 1]?.id}`}
        ref={scrollViewRef}
      >
        <View className='messages-list'>
          {messages.map((message) => (
            <View 
              key={message.id}
              id={`msg-${message.id}`}
              className={`message-item ${message.role}`}
            >
              {message.role === 'assistant' && (
                <View className='message-avatar'>
                  <Text className='avatar-text'>🏛️</Text>
                </View>
              )}
              <View className='message-content'>
                {/* 思考过程 */}
                {message.reasoning && (
                  <View className='message-reasoning'>
                    <View 
                      className='reasoning-header'
                      onClick={() => toggleReasoning(message.id)}
                    >
                      <Text className='reasoning-title'>💭 思考过程</Text>
                      <Text className='reasoning-toggle'>
                        {message.reasoningCollapsed ? '展开 ▼' : '收起 ▲'}
                      </Text>
                    </View>
                    {!message.reasoningCollapsed && (
                      <Text className='reasoning-text'>{message.reasoning}</Text>
                    )}
                  </View>
                )}
                {/* 回复内容 */}
                <Text className='message-text'>{message.content}</Text>
                <Text className='message-time'>
                  {new Date(message.timestamp).toLocaleTimeString(state.locale === 'zh' ? 'zh-CN' : 'en-US', {
                    hour: '2-digit',
                    minute: '2-digit'
                  })}
                </Text>
              </View>
              {message.role === 'user' && (
                <View className='message-avatar'>
                  <Text className='avatar-text'>👤</Text>
                </View>
              )}
            </View>
          ))}
          
          {isLoading && (
            <View className='message-item assistant'>
              <View className='message-avatar'>
                <Text className='avatar-text'>🏛️</Text>
              </View>
              <View className='message-content'>
                <View className='typing-indicator'>
                  <View className='typing-dot' />
                  <View className='typing-dot' />
                  <View className='typing-dot' />
                </View>
                <Text className='message-time'>{i18n.chat.thinking}</Text>
              </View>
            </View>
          )}
        </View>
      </ScrollView>

      {/* 输入区域 */}
      <View className='input-area'>
        <View className='input-wrapper'>
          <Input
            className='chat-input'
            type='text'
            value={inputValue}
            placeholder={i18n.chat.placeholder}
            onInput={(e) => setInputValue(e.detail.value)}
            onConfirm={handleSend}
            disabled={isLoading}
            maxlength={500}
          />
          <View 
            className={`send-button ${(!inputValue.trim() || isLoading) ? 'disabled' : ''}`}
            onClick={handleSend}
          >
            <Text className='send-button-text'>{i18n.chat.send}</Text>
          </View>
        </View>
      </View>
    </View>
  )
}

export default ArtifactChat

